// pages/voucher/voucher.js
var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
var mph = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    voucher_list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that =this;
    //代金券列表,数据来源.
    if (options.store_id){
    var url = ApiUrl +'index.php?act=voucher&op=voucher_tpl_list'
    mph.postRequest(url, { store_id: options.store_id },function (res){
      if(res.data.code==200){
        that.setData({
          voucher_list: res.data.datas.voucher_list
        })
      }
    
    });
    } 
  },

  /** 
   * 领取优惠券
   */
  getvoucher:function(e){
    var that =this;
    var url = 'index.php?act=member_voucher&op=voucher_freeex';
    that.addToWeiXinCard(e.currentTarget.dataset.index);
    mph.postRequest(url, { tid: e.currentTarget.dataset.tid }, function (res){
      
          if (res.data.code == 200) {
            mph.showSuccess('领取成功');
          } 
    })
  },

  addToWeiXinCard(i){
    let that = this;
    let voucher_list = that.data.voucher_list;
    //let {card_id,code,timestamp,openid,nonce_str,signature,fixed_begintimestamp} = that.data.wxCardData;
    //let cardExt = {code,openid,timestamp,nonce_str,fixed_begintimestamp,signature,outer_str:'miniProgram'}
    
    //console.log(card_id);
    wx.addCard({
      cardList: [{
        cardId:voucher_list[i].voucher_t_id,
        cardExt:JSON.stringify(voucher_list[i])
      }],
      success(res){
        console.log(res);
        that.addCardSuccess(res.cardList[0].code)
      },
      fail(err){
        console.log(err);
      }
    })
  },
})